<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
    <el-tree :data="menus" show-checkbox node-key="catId" :expand-on-click-node="false" :props="defaultPropes"
      :filter-node-method="filterNode" ref="tree" :accordion="true" :default-expanded-keys="expandKey" v-loading="loading"
      element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
      :draggable="draggable" :allow-drop="allowDrop" @node-drop="handleDrop">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level<=2" type="text" icon="el-icon-circle-plus" size="mini" @click="()=>openDialog(node)"></el-button>
          <el-button v-if="node.childNodes.length==0" type="text" icon="el-icon-delete" circle size="mini" @click="() => remove(node, data)"></el-button>
          <el-button v-if="" type="text" icon="el-icon-edit" size="mini" @click="() => queryDataByCatId(node)"></el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="category">
        <el-form-item label="分类名称" >
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="() => submit(category)">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

  export default {
    // import引入的组件需要注入到对象中才能使用
    components: {},
    props: {},
    data() {
      return {
        menus: [],
        defaultPropes: {
          children: "children",
          label: "name"
        },
        filterText: "",
        expandKey: [],
        loading: true,
        dialogFormVisible: false,
        category: {
          catId: null,
          name: "",
          parentCid: "",
          catLevel: "",
          icon: "",
          productUnit: "",
          productCount: "",
          sort: 0,
        },
        formLabelWidth: '120px',
        pCid: [],
        draggable: false,
        updateNodes: [],
        maxLevel: 0,
        title: "",
        dialogType: "", //edit,add
      };
    },

    // 计算属性类似于data概念
    computed: {},
    // 监控data中的数据变化
    watch: {
      //过滤出节点
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    // 方法集合
    methods: {

      getMenus() {
        this.$http({
          url: this.$http.adornUrl('/product/pmscategory/list/getTree'),
          method: 'get'
        }).then(({
          data
        }) => {
          console.log(data);
          this.menus = data.tree;
          this.loading = false;
        })
      },

      //打开添加对话框
      openDialog(node) {
        console.log(node);
        this.dialogType = "add";
        this.title = "添加分类";
        this.dialogFormVisible = true;
        this.category.parentCid = node.data.catId;
        this.category.catLevel = node.level + 1;
      },

      //关闭对话框
      closeDialog() {
        this.dialogFormVisible = false;
        this.category = {};
        this.title = "";
      },

      //提交
      submit(category) {
        if (this.dialogType == 'add') {
          this.add(category);
        };
        if (this.dialogType == 'update') {
          this.update(category);
        }
      },
      //添加分类
      add(category) {
        console.log(category);
        this.dialogFormVisible = false;
        this.$http({
          url: this.$http.adornUrl(`/product/pmscategory/save`),
          method: 'post',
          data: category
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500,
            });
            this.getMenus();
            this.expandKey = [category.parentCid];
            this.category = {};
          } else {
            this.$message.error(data.msg);
          }
        });
      },

      //修改分类
      update(category) {
        console.log(category);
        this.dialogFormVisible = false;
        this.$http({
          url: this.$http.adornUrl(`/product/pmscategory/update`),
          method: 'post',
          data: category
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500,
            });
            this.getMenus();
            this.expandKey = [category.parentCid];
            this.category = {};
          } else {
            this.$message.error(data.msg);
          }
        });
      },

      //删除分类
      remove(node, data) {
        this.$confirm(`确定删除【${data.name}】吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/pmscategory/delete'),
            method: 'post',
            data: [node.data.catId]
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: data.msg,
                type: 'success',
                duration: 1500
              });
              this.getMenus();
              this.expandKey = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg);
            }
          })
        }).catch(() => {

        })
      },

      //过滤查询关键字
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },

      //根据catId查询分类明细
      queryDataByCatId(node) {
        this.dialogType = "update";
        this.title = "修改分类";
        this.dialogFormVisible = true;
        this.$http({
          url: this.$http.adornUrl(`/product/pmscategory/info/${node.data.catId}`),
          method: 'get'
        }).then(({
          data
        }) => {
          console.log(data);
          if (data && data.code === 0) {
            /* this.$message({
              message: data.msg,
              type: 'success',
              duration: 1500
            }); */
            this.category = data.pmsCategory;
          } else {
            this.$message.error(data.msg);
          }
        })
      },

      //批量删除
      batchDelete() {
        let catIds = [];
        let checkedNodes = this.$refs.tree.getCheckedNodes();
        console.log("被选中的元素", checkedNodes);
        for (let i = 0; i < checkedNodes.length; i++) {
          catIds.push(checkedNodes[i].catId);
        }
        this.$confirm(`是否批量删除【${catIds}】菜单?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            this.$http({
              url: this.$http.adornUrl("/product/pmscategory/delete"),
              method: "post",
              data: this.$http.adornData(catIds, false)
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: data.msg,
                  type: "success"
                });
              } else {
                this.$message.error(data.msg);
              }
              this.getMenus();
            });
          }).catch(() => {});
      },
      
      //批量更新
      batchSave() {
        this.$http({
          url: this.$http.adornUrl("/product/pmscategory/update/sort"),
          method: "post",
          data: this.$http.adornData(this.updateNodes, false)
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.$message({
              message: data.msg,
              type: "success"
            });
          } else {
            this.$message.error(data.msg);
          }
          //刷新出新的菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = this.pCid;
          this.updateNodes = [];
          this.maxLevel = 0;
        });
      },
      
      //处理拖拽
      handleDrop(draggingNode, dropNode, dropType, ev) {
        console.log("handleDrop: ", draggingNode, dropNode, dropType);
        //1、当前节点最新的父节点id
        let pCid = 0;
        let siblings = null;
        if (dropType == "before" || dropType == "after") {
          pCid = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId;
          siblings = dropNode.parent.childNodes;
        } else {
          pCid = dropNode.data.catId;
          siblings = dropNode.childNodes;
        }
        this.pCid.push(pCid);

        //2、当前拖拽节点的最新顺序，
        for (let i = 0; i < siblings.length; i++) {
          if (siblings[i].data.catId == draggingNode.data.catId) {
            //如果遍历的是当前正在拖拽的节点
            let catLevel = draggingNode.level;
            if (siblings[i].level != draggingNode.level) {
              //当前节点的层级发生变化
              catLevel = siblings[i].level;
              //修改他子节点的层级
              this.updateChildNodeLevel(siblings[i]);
            }
            this.updateNodes.push({
              catId: siblings[i].data.catId,
              sort: i,
              parentCid: pCid,
              catLevel: catLevel
            });
          } else {
            this.updateNodes.push({
              catId: siblings[i].data.catId,
              sort: i
            });
          }
        }

        //3、当前拖拽节点的最新层级
        console.log("updateNodes", this.updateNodes);
      },
      
      //需要更新的节点
      updateChildNodeLevel(node) {
        if (node.childNodes.length > 0) {
          for (let i = 0; i < node.childNodes.length; i++) {
            var cNode = node.childNodes[i].data;
            this.updateNodes.push({
              catId: cNode.catId,
              catLevel: node.childNodes[i].level
            });
            this.updateChildNodeLevel(node.childNodes[i]);
          }
        }
      },
      
      //计算允许拖拽
      allowDrop(draggingNode, dropNode, type) {
        console.log("allowDrop:", draggingNode, dropNode, type);
        this.countNodeLevel(draggingNode);
        //当前正在拖动的节点+父节点所在的深度不大于3即可
        let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
        console.log("深度：", deep);
        if (type == "inner") {
          return deep + dropNode.level <= 3;
        } else {
          return deep + dropNode.parent.level <= 3;
        }
      },
      
      //计算节点深度
      countNodeLevel(node) {
        //找到所有子节点，求出最大深度
        if (node.childNodes != null && node.childNodes.length > 0) {
          for (let i = 0; i < node.childNodes.length; i++) {
            if (node.childNodes[i].level > this.maxLevel) {
              this.maxLevel = node.childNodes[i].level;
            }
            this.countNodeLevel(node.childNodes[i]);
          }
        }
      }

    },
    // 生命周期-创建完成（可以访问当前this实例）
    created() {
      this.getMenus();
    },
    // 生命周期-挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, // 生命周期-创建之前
    beforeMount() {}, // 生命周期-挂载之前
    beforeUpdate() {}, // 生命周期-更新之前
    updated() {}, // 生命周期-更新之后
    beforeDestroy() {}, // 生命周期-销毁之前
    destroyed() {}, // 生命周期-销毁完成
    activated() {} // 如果页面有keep-alive缓存功能，这个函数会触发
  };
</script>

<style>
</style>
